package com.fyi.springbootmongocomment.service.impl;

import com.fyi.springbootmongocomment.dao.CommentDao;
import com.fyi.springbootmongocomment.pojo.Comment;
import com.fyi.springbootmongocomment.service.CommentService;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CommentDao commentDao;
    //查询所有
    @Override
    public List<Comment> selectAll() {

        return commentDao.findAll();
    }

    //删除
    @Override
    public long del(String _id) {
        Query query = new Query(Criteria.where("_id").is(_id));
        DeleteResult remove = mongoTemplate.remove(query, Comment.class);
        long count = remove.getDeletedCount();
        return count;
    }


    //修改
    @Override
    public void updateComment(Comment comment) {
        commentDao.save(comment);

    }
    //添加
    @Override
    public Integer add(Comment comment) {
        Comment insert = mongoTemplate.insert(comment);
        if (insert == null){
            return 1;
        }
        return 0;
    }
    @Override
    public Comment selectCommentById(String id) {
        return commentDao.findById(id).get();
    }

    @Override
    public Page<Comment> findCommentListPageByParentid(String parentid, int page, int size) {
        return commentDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }

    @Override
    public void updateCommentLikenumThumbup(String id) {
        //查询对象
        Query query=Query.query(Criteria.where("_id").is(id));
        //更新条件
        Update update = new Update();
        update.inc("likenum");
        //执行更新
        mongoTemplate.updateFirst(query,update,"comment");
    }
}
